import axios from 'axios';
import env from '../../config/dev.env.js';
import iView from 'iview';
import md5 from 'js-md5';

let util = {
	
};

const baseUrl = 'https://api.xiaozhe.cn/';
const ajaxUrl = env === 'development' ? baseUrl +'api.php' : baseUrl +'api.php' ;

// 基础地址
util.baseUrl = baseUrl;
// 上传地址
util.upload = ajaxUrl;

util.ajax = axios.create({
    baseURL: ajaxUrl,
    timeout: 30000
});

util.ajax = axios.create({
    baseURL: ajaxUrl,
    params: {},
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    timeout: 30000
});

// 请求拦截器
util.ajax.interceptors.request.use(
    config => {
       	config.params['token'] = localStorage.token;
       	config.params['timestamp'] = parseInt(new Date().getTime());
       	// 此处用于解决在application/json模式下data数据问题（问题为data会变成"{name: 'wx'}:"，而不是"{name: 'wx'}"）
    	config.transformRequest = function(data) {
    		let result = [];
	        for (let it in data) {
	        	result.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]));
	        }
        	return result.join('&');
    	}
       	iView.LoadingBar.start();
        return config;
    }
);

// 响应拦截器
util.ajax.interceptors.response.use(
    response => {
        iView.LoadingBar.finish();
        if(response.data.code !== 200) {
            iView.Message.error(response.data.message);
            return Promise.reject();
        }
        return response.data.result;
    },
    error => {
        iView.LoadingBar.error();
        return Promise.reject();
    }
);

util.sign = function(token, timestamp, data) {
    // 签名格式： timestamp + token + data(字典升序)
    let ret = [];
    for(let it in data) {
        let val = data[it];
        if(typeof val === 'object' &&
            (!(val instanceof Array) || (val.length > 0 && ('object' === typeof val[0])))) {
            val = JSON.stringify(val);
        }

        ret.push((it + "=" + val));
    }

    // 字典升序
    ret.sort();
    let signsrc = ret.join('&');
    return md5(timestamp + token + signsrc);
}

export default util;